package opmq

import (
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

// ClusterMessage 集群处理消息的格式
type ClusterMessage struct {
	Topic   string
	PayLoad []byte
}

type ClusterNode struct {
	Id string `json:"id"`

	Ip     string `json:"ip"`
	// mqtt端口号
	Port   string `json:"port"`
	Topics []string `json:"topics"`
}

func NewClusterNode(id string, ip string, port string, topic []string) *ClusterNode {
	cn := &ClusterNode{
		Id:     id,
		Ip:     ip,
		Port:   port,
		Topics: topic,
	}

	return cn
}

func (cn *ClusterNode) Send(topic string, data []byte) {
	CLUSTER_DEBUG.Println("转发数据: ", topic, len(data), "ip: ", cn.Ip, " port: ", cn.Port)

	opts := mqtt.NewClientOptions().AddBroker("tcp://" + cn.Ip + ":" + cn.Port)
	//opts.SetAutoReconnect(true)
	opts.SetKeepAlive(time.Second * 120)
	opts.SetClientID(time.Now().String())

	c := mqtt.NewClient(opts)
	token := c.Connect()
	defer c.Disconnect(250)
	if token.Wait() && token.Error() != nil {
		CLUSTER_PANIC.Println("建立mq连接失败", token.Error())
		return
	}

	CLUSTER_DEBUG.Println(cn.Id, "节点发送数据，topic: ", topic, " payload字节: ", len(data))
	c.Publish(topic, 0, false, data)
}
